package biz

import (
	"context"
	"database/sql"

	"github.com/go-kratos/kratos/contrib/registry/consul/v2"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/hashicorp/consul/api"
	"gorm.io/gorm"

	"gitee.com/architect-training/substitute-driver/customer-srv/api/valuation"
)

const (
	CustomerSecret = "yourSecretKey"
	TokenDuration  = 2 * 30 * 24 * 3600
)

// Customer 顾客实体结构体
type Customer struct {
	// 基础字段
	gorm.Model

	CustomerWork // 业务逻辑

	CustomerToken // token部分
}

// CustomerWork 业务逻辑部分
type CustomerWork struct {
	Telephone string         `gorm:"type:varchar(15);uniqueIndex;" json:"telephone"`
	Name      sql.NullString `gorm:"type:varchar(255);uniqueIndex;" json:"name"`
	Email     sql.NullString `gorm:"type:varchar(255);uniqueIndex;" json:"email"`
	Wechat    sql.NullString `gorm:"type:varchar(255);uniqueIndex;" json:"wechat"`
	CityID    uint           `gorm:"index;" json:"cityID"`
}

// CustomerToken token 部分
type CustomerToken struct {
	Token          string       `gorm:"type:varchar(4095);" json:"token"`
	TokenCreatedAt sql.NullTime `gorm:"" json:"token_created_at"`
}

type CustomerBiz struct {
}

func NewCustomerBiz() *CustomerBiz {
	return &CustomerBiz{}
}

func (cb *CustomerBiz) GetEstimatePrice(origin, destination string) (int64, error) {
	consulConfig := api.DefaultConfig()
	consulConfig.Address = "localhost:8500"
	consulClient, err := api.NewClient(consulConfig)
	dis := consul.New(consulClient)
	if err != nil {
		return 0, err
	}

	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint(ValuationServiceName),
		grpc.WithDiscovery(dis),
	)
	if err != nil {
		return 0, nil
	}
	defer func() {
		_ = conn.Close()
	}()

	client := valuation.NewValuationClient(conn)
	reply, err := client.GetEstimatePrice(context.Background(), &valuation.GetEstimatePriceReq{
		Origin:      origin,
		Destination: destination,
	})
	if err != nil {
		return 0, err
	}

	return reply.Price, nil
}
